import axios from 'axios'
import qs from 'qs'



// 创建axios实例对象
const instance = axios.create({
    baseURL:'https://api.vvhan.com/api',
    timeout: 5000,
})

// 请求拦截器
instance.interceptors.request.use(config => {
    console.log(config);
    return config
})
// 响应拦截器
instance.interceptors.response.use(res => {
    console.log(res);
    return res
})
// 封装ajax请求
let request = function ({ method, url, params, headerType }) {
    let data = {}
    // 判断是否需要添加token
    if(url != 'login'){
        instance.interceptors.request.use((config)=>{
            console.log(config);
            config.headers.Authorization = window.sessionStorage.getItem('token')
            return config
        })
    }
    // 如果请求方式是get请求
    if (method.toLowerCase() == 'get') {
        // 那么设置get的请求头
        if (headerType == 'form') {
            instance.defaults.headers["Content-Type"] = "application/x-www-form-urlencoded;charset=utf-8";
        }
        // 利用qs将其序列化为key=value的格式
        url = url + '?' + qs.stringify(params)
    }

    if (method.toLowerCase() == 'post') {
        // 那么设置post的请求头
        if (headerType == 'form') {
            instance.defaults.headers["Content-Type"] = "application/x-www-form-urlencoded;charset=utf-8";
            data = qs.stringify(params)
        } else {
            instance.defaults["Content-Type"] = "application/json;charset=utf-8";
            data = params;
        }
    }
    // return 一个promise对象 jie'shoiu
    return new Promise((resolve, reject) => {
        instance({
            method, url, params,data
        }).then(res => {
            resolve(res)
        }).catch(err => {
            console.log(err);
            reject(err)
        })

    })
}

export default request

